package paa.simulator.model;

import java.util.Collection;
import java.util.Iterator;

import paa.simulator.RandomNumberGenerator;
import paa.simulator.grafo.PessoaVertex;
import paa.simulator.grafo.simple.PessoaEdge;
import paa.simulator.grafo.simple.UndirectedSimpleGraph;

public class LinearThresholdModel extends AbstractModel {

	private final double threshold;

	public LinearThresholdModel(double threshold) {
		this.threshold = threshold;
	}
	
	public boolean executeTurn(UndirectedSimpleGraph<PessoaVertex> graph) {
		boolean changedOpinions = false;
		
		for (PessoaVertex pv : graph.vertexSet()) {
			if (!pv.isBuying()) {
				Collection<PessoaEdge<PessoaVertex>> edges = graph.edgesOf(pv);
				
				double sum = 0;
				Iterator<PessoaEdge<PessoaVertex>> it = edges.iterator();
				while (it.hasNext()) {
					PessoaEdge<PessoaVertex> next = it.next();
					PessoaVertex other = next.getRelation(pv);
					
					if (other.isBuying()) {
						sum += next.getWeight();
					}
				}	
					
				if (sum >= threshold) {
					setAsBuying(pv, graph);
					changedOpinions = true;
				}
			}
		}
		
		return changedOpinions;
	}

	public void initiateGraph(UndirectedSimpleGraph<PessoaVertex> graph) {
		for (PessoaVertex pv : graph.vertexSet()) {
			Collection<PessoaEdge<PessoaVertex>> edges = graph.edgesOf(pv);
			
			int nEdges = edges.size();
			double[] randomNumbers = new double[nEdges];
			
			double sum = 0;
			for (int i = 0; i < nEdges; i++) {
				randomNumbers[i] = RandomNumberGenerator.getInstance().nextDouble();
				sum += randomNumbers[i]; 
			}
			
			Iterator<PessoaEdge<PessoaVertex>> it = edges.iterator();
			int i = 0;
			while (it.hasNext()) {
				PessoaEdge<PessoaVertex> edge = it.next();
				edge.setWeight(randomNumbers[i] / sum);
				i++;
			}
		}
	}
}
